package com.eudon.ai.agent.tools;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author eudon
 * @description 该工具在AI识别需要联网查询的时候进行调用
 * @date 2025/8/19
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
@Slf4j
public class SearchTool {
    private final String API_KEY;

    public SearchTool(String apiKey) {
        API_KEY = apiKey;
    }

    @Tool(description = "search on the internet")
    public String searchOnInternet(@ToolParam(description = "question") String question) {
        OkHttpClient client = new OkHttpClient();

        HttpUrl.Builder urlBuilder = HttpUrl.get("https://www.searchapi.io/api/v1/search").newBuilder();
        urlBuilder.addQueryParameter("engine", "baidu");
        urlBuilder.addQueryParameter("q", question);
        urlBuilder.addQueryParameter("api_key", API_KEY);

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body != null) {
                JSONObject object = JSONUtil.parseObj(body.string());
                JSONArray jsonArray = JSONUtil.parseArray(object.get("organic_results"));
                List<Object> needList = jsonArray.size() > 3 ? jsonArray.subList(0, 3) : jsonArray;
                return needList.stream()
                        .map(JSONUtil::parse)
                        .map(JSON::toString)
                        .collect(Collectors.joining(","));
            }
            return "search nothing for user`s question ,please generate a correct answer for user";
        } catch (Exception e) {
            return "search nothing for user`s question ,please generate a correct answer for user";
        }

    }
}
